# Copyright 2023 Garena Online Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,

# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility code to be used by integrals."""

import jax.numpy as jnp
import numpy as np
import scipy.special

# for horizontal recursion
_r50 = np.arange(50)
comb = jnp.array(scipy.special.comb(_r50[:, None], _r50[None]))


def py_scan(f, init, xs, length=None):
  """lax.scan is slow"""
  if xs is None:
    xs = [None] * length
  carry = init
  ys = []
  for x in xs:
    carry, y = f(carry, x)
    ys.append(y)
  return carry, jnp.stack(ys)
